<template>
    <section>

        <!--高级查询-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="searchForm">
                <el-form-item>
                    <el-input v-model="searchForm.name" placeholder="姓名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="searchForm.state" clearable placeholder="请选择状态">
                        <el-option label="启用" value="0"></el-option>
                        <el-option label="禁用" value="-1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="getDepartments">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="department" highlight-current-row v-loading="listLoading" @selection-change="selsChange"style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60" label="序号">
            </el-table-column>
            <el-table-column prop="name" label="姓名">
            </el-table-column>
            <el-table-column prop="sn" label="部门编号" >
            </el-table-column>
            <el-table-column prop="state" label="状态" :formatter="formatSex">
            </el-table-column>
            <el-table-column prop="parent.name" label="上级部门" >
            </el-table-column>
            <el-table-column prop="manager.username" label="部门经理">
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
            </el-pagination>
        </el-col>


        <!--新增/编辑界面-->
        <el-dialog :title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
            <el-form :model="addForm" label-width="80px" :rules="rules" ref="ruleForm">
                <el-form-item label="部门" prop="name">
                    <el-input v-model="addForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="编号" prop="sn">
                    <el-input v-model="addForm.sn"  auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="addForm.state">
                        <el-radio class="radio" :label="0">启用</el-radio>
                        <el-radio class="radio" :label="-1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="部门经理" prop="managerId">
                    <el-select v-model="addForm.managerId" clearable placeholder="请选择">
                        <el-option
                                v-for="item in manager"
                                :key="item.id"
                                :label="item.username"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上级部门">
                    <el-cascader v-model="addForm.path"
                            :options="options"
                            :props="{ checkStrictly: true }"
                            clearable>
                    </el-cascader>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="addSubmit" >提交</el-button>
            </div>
        </el-dialog>
        </section>
</template>



<script>
    import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

    export default {
        data() {
            return {
                //校验规则
                rules:{
                    name:[
                        { required: true, message: '部门名必填', trigger: 'blur' }
                    ],
                    sn:[
                        { required: true, message: '部门编号必填', trigger: 'blur' }
                    ],
                    managerId:[
                        { required: true, message: '部门经理必填', trigger: 'change' }
                    ]
                },
                //上级部门
                options:[],
                //部门经理
                manager:[],
                //新增/编辑的form表单
                addForm:{
                    //主键id
                    id:"",
                    //部门名
                    name:"",
                    //部门编号
                    sn:"",
                    //状态
                    state:"",
                    //部门经理id
                    managerId:"",
                    //上级部门
                    path:""
                },
                //新增和编辑模态框默认为不弹出
                addFormVisible:false,
                //新增和编辑标题
                title:"",
                //高级查询表单数据
                searchForm:{
                    name:"",
                    state:""
                },
                //是否加载
                listLoading:false,
                ////列表选中列
                sels:[],
                //列表展示
                department:[],
                //每页条数
                pageSize:10,
                //当前页
                currentPage:1,
                //总条数
                total:0
            }
        },
        methods: {
            //给新增和编辑模态框的提交按钮注册事件
            addSubmit(){
                //创建一个manager对象
                let manager={"id":this.addForm.managerId};
                //给addForm添加manager属性
                this.addForm.manager=manager;
                //拿到path
                let path=this.addForm.path
                //创建一个parent对象
                let parent={"id":path[path.length-1]};
                //给addForm添加parent属性
                this.addForm.parent=parent
                //把path数组转化为字符串方便后台存值
                this.addForm.path=path.toString();
               /* console.debug(this.addForm.path)*/
                //校验addForm表单
                this.$refs["ruleForm"].validate((valid) => {
                        if (valid) {//校验成功
                            this.$http.post("/department",this.addForm).then(res=>{
                                let{success,msg}=res.data;
                                if(success){
                                    this.$message({
                                        type: success,
                                        message: '添加成功'
                                    });
                                    //关闭模态框
                                    this.addFormVisible=false;
                                    //添加成功，重新加载列表
                                    this.loadDepartments();
                                    //重新加载上级部门
                                    this.loadNextDepartment();
                                }else{//打印错误
                                    this.$message.error(msg);
                                }
                            })
                        }
                });
            },
            //给新增按钮绑定事件
            handleAdd(){
                //给新增标题赋值
                this.title="新增";
                //重置表单校验属性
                if(this.$refs["ruleForm"]) {
                    this.$refs["ruleForm"].resetFields();
                }
                //重置普通属性
                for(var i in this.addForm){
                    this.addForm[i]="";
                }
                //弹出新增模态框
                this.addFormVisible=true;
                //状态默认为启用
                this.addForm.state=0;
            },
            //给高级查询按钮绑定事件
            getDepartments(){
                //设置查询页码为第一页
                this.currentPage=1;
                //加载查询的部门列表
                this.loadDepartments();
            },
            //勾选复选框时触发此函数
            selsChange(sels){
                /*console.debug(sels)*/
                this.sels = sels;
            },
            //批量删除
            batchRemove(){
                /*console.debug(this.sels)*/
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {//点击确定执行里面的代码
                    this.$http.patch("/department/delete",this.sels).then(res=>{
                        //回调函数和解构表达式
                        let {success,msg}=res.data
                        if(success){
                            this.$message({
                                type: success,
                                message: '删除成功'
                            });
                     //删除成功，重新加载列表
                       this.loadDepartments();
                        }else{//打印错误
                            this.$message.error(msg);
                        }
                    })
                }).catch(() => {//点击取消执行里面代码
                });
            },
            //页码改变时，执行此函数
            handleCurrentChange(val){
                this.currentPage=val
                //继续分页查询
                this.loadDepartments();
            },
            //状态显示转换
            formatSex(row){
               return row.state==0?"启用":"禁用"
            },

           //给编辑按钮添加事件
            handleEdit(index,row){
                /*console.debug(row);*/
                //给标题设置值
                this.title="编辑"
                //回显普通数据
                for(var i in this.addForm){
                    this.addForm[i]=row[i]
                };
                //判断manager是否为null
                if(row.manager!=null){
                    this.addForm.managerId=row.manager.id;
                }
                //特定属性回显
                //判断path是否为null
                if(this.addForm.path!=null){
                //把路径转化为数字数组
                    console.debug(this.addForm.path.split(","))
                this.addForm.path=this.addForm.path.split(",").map(Number);
                console.debug(this.addForm.path)
                }
                //弹出模态框
                this.addFormVisible=true;
            },
            //给删除按钮添加事件
            handleDel(index,row){
                console.debug(index,row)
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {//点击确定执行里面的代码
                    this.$http.delete("/department/"+row.id).then(res=>{
                        //回调函数和解构表达式
                        let {success,msg}=res.data
                        if(success){
                            this.$message({
                                type: success,
                                message: '删除成功'
                            });
                            //删除成功，重新加载列表
                            this.loadDepartments();
                        }else{//打印错误
                            this.$message.error(msg);
                        }
                    })
                }).catch(() => {//点击取消执行里面代码
                });
            },
            //加载部门列表
            loadDepartments(){
                //显示加载
                this.listLoading=true;
                let parm={
                    "currentPage":this.currentPage,
                    "pageSize":this.pageSize,
                    "name":this.searchForm.name,
                    "state":this.searchForm.state
                }
                this.$http.patch("/department",parm).then(res=>{
                    //关闭加载
                    this.listLoading=false;
                    /*console.debug(res)*/
                    let{total,list}=res.data
                    this.total=total,
                    this.department=list
                })
            },
            //查询所有的部门经理
            loadEmployees(){
                this.$http.patch("/department/employees").then(res=>{
                    this.manager=res.data;
                })
            },
            //查询上级部门
            loadNextDepartment(){
                this.$http.patch("/department/nextDepartment").then(res=>{
                    console.debug(res.data)
                    this.options=res.data;
                })
            }
        },
        mounted() {
            this.loadDepartments();
            //加载部门经理
            this.loadEmployees();
            //加载上级部门
            this.loadNextDepartment();
        }
    }

</script>